package leetcode.offer_two_special.integer;

/**
 * @author mazouri
 * @create 2021-09-04 21:20
 */
public class _02_addBinary {
    public String addBinary(String a, String b) {
        StringBuilder res = new StringBuilder();
        int n = Math.max(a.length(), b.length());
        int carry = 0;

        for (int i = 0; i < n; i++) {
            int aChar = a.length() > i ? a.charAt(a.length() - i - 1) - '0' : 0;
            int bChar = b.length() > i ? b.charAt(b.length() - i - 1) - '0' : 0;

            int sum = aChar + bChar + carry;
            carry = sum >= 2 ? 1 : 0;
            sum = sum >= 2 ? sum - 2 : sum;

            res.append(sum);
        }

        if (carry == 1) res.append(1);

        return res.reverse().toString();
    }
}
